import argparse
import json

from torch.utils.data import DataLoader
from models import *
from utils.datasets import *
from utils.utils import *
from voc_eval import _do_python_eval

def test(cfg,
         data,
         weights=None,
         batch_size=16,
         img_size=416,
         conf_thres=0.001,
         nms_thres=0.5,
         save_json=False,
         model=None,
         dataloader=None,
         opt=None):
    # Initialize/load model and set device
    if model is None:
        device = torch_utils.select_device(opt.device, batch_size=batch_size)
        verbose = True

        # Remove previous
        for f in glob.glob('test_batch*.jpg'):
            os.remove(f)

        # Initialize model
        model = Darknet(cfg, img_size, quan=opt.quan).to(device)
        # print(model.module_list)
        
        # Load weights
        # attempt_download(weights)
        if weights.endswith('.pt'):  # pytorch format
            model.load_state_dict(torch.load(weights, map_location=device)['model'])
        else:  # darknet format
            _ = load_darknet_weights(model, weights)

        # if torch.cuda.device_count() > 1:
        #     model = nn.DataParallel(model)
    else:  # called by train.py
        device = next(model.parameters()).device  # get model device
        verbose = False

    # Configure run
    data = parse_data_cfg(data)
    nc = int(data['classes'])  # number of classes
    path = data['valid']  # path to test images
    names = load_classes(data['names'])  # class names

    # Dataloader
    if dataloader is None:
        dataset = LoadImagesAndLabels(path, img_size, batch_size, rect=False, cache_labels=True, cache_images=opt.cache_images)
        batch_size = min(batch_size, len(dataset))
        dataloader = DataLoader(dataset,
                                batch_size=batch_size,
                                # num_workers=min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]),
                                num_workers=16,
                                pin_memory=True,
                                collate_fn=dataset.collate_fn)

    model.eval()
    s = ('%20s' + '%10s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@0.5', 'F1')
    loss = torch.zeros(3)
    jdict = []
    
    if opt.prune:
        prune_weight(model, opt.percent)
    
    if opt.quan:
        quan_weight(model)
    
    for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
        imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
        targets = targets.to(device)
        _, _, height, width = imgs.shape  # batch size, channels, height, width

        # Disable gradients
        with torch.no_grad():
            # Run model
            inf_out, train_out = model(imgs)  # inference and training outputs

            # Compute loss
            if hasattr(model, 'hyp'):  # if model has loss hyperparameters
                loss += compute_loss(train_out, targets, model)[1][:3].cpu()  # GIoU, obj, cls
            # Run NMS
            output = non_max_suppression(inf_out, conf_thres=conf_thres, nms_thres=nms_thres)

        # Statistics per image
        for si, pred in enumerate(output):
            if pred is None:
                continue
            # Clip boxes to image bounds
            clip_coords(pred, (height, width))
            # Append to pycocotools JSON dictionary
            # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
            box = pred[:, :4].clone()  # xyxy
            scale_coords(imgs[si].shape[1:], box, shapes[si][0], shapes[si][1])  # to original shape
            for di, d in enumerate(pred):
                jdict.append({'image_id': Path(paths[si]).stem,
                              'category_id': int(d[5]),
                              'bbox': [floatn(x, 3) for x in box[di]],
                              'score': floatn(d[4], 5)})

    # Save JSON
    if len(jdict):
        names_list = []
        with open(data['names'], 'r') as fp:
            lines = fp.readlines()
        for line in lines:
            line = line.rstrip()
            names_list.append(line)

        fps = [0]*len(names_list)
        if not os.path.exists('results'):
            os.mkdir('results')
        for i in range(len(names_list)):
            buf = 'results/comp4_det_test_%s.txt' % (names_list[i])
            fps[i] = open(buf, 'w')

        for item in jdict:
            x1, y1, x2, y2 = item['bbox']
            prob = item['score']
            cls_id = item['category_id']
            fileId = item['image_id']
            fps[cls_id].write('%s %f %f %f %f %f\n' % (fileId, prob, x1, y1, x2, y2))

        for i in range(len(names)):
            fps[i].close()

        mAP = _do_python_eval("results/comp4_det_test_", output_dir = 'output')
    else:
        print("error!")
        mAP = 0
    
    # Return results
    return (0, 0, mAP, 0, *(loss / len(dataloader)).tolist())


if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='test.py')
    parser.add_argument('--cfg', type=str, default='cfg/yolov3_ReLU-voc.cfg', help='*.cfg path')
    parser.add_argument('--data', type=str, default='data/voc.data', help='*.data path')
    parser.add_argument('--weights', type=str, default='/home/zhangjm/backup/yolov3_ReLU_voc/yolov3_ReLU-voc_final.weights', help='path to weights file')
    parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch')
    parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
    parser.add_argument('--nms-thres', type=float, default=0.5, help='iou threshold for non-maximum suppression')
    parser.add_argument('--device', default='3', help='device id (i.e. 0 or 0,1) or cpu')
    #############
    parser.add_argument('--quan', action='store_true', help='quantize the model')
    parser.add_argument('--prune', action='store_true', help='prune the model')
    parser.add_argument('--percent', type=float, default=0.1)
    parser.add_argument('--cache-images', default=False, help='cache-images')
    # parser.add_argument('--names', type=str, default='/home/zjm/darknet/data/voc.names')
    opt = parser.parse_args()
    print(opt)

    test(opt.cfg,
         opt.data,
         opt.weights,
         opt.batch_size,
         opt.img_size,
         opt.conf_thres,
         opt.nms_thres,
         opt=opt)